package com.tyrone.concurrent.basic.databaseConnectionPool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.concurrent.TimeUnit;

/**
 * 由于我们正常来说，数据库驱动提供方来实现的。这里直接用动态代理构建一个Connection
 */
public class ConnectionDriver {
    static class ConnectionHandler implements InvocationHandler{
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // 如果是commit方法执行以下
            if(method.getName().equals("commit")){
                System.out.println("开始提交事务");
                TimeUnit.MILLISECONDS.sleep(100);
                System.out.println("事提交完成");
            }
            return null;
        }
    }

    public static final Connection createConnection(){
        return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(),
                new Class<?>[]{Connection.class},new ConnectionHandler());
    }
}
